import React, { Component } from 'react'
import Pubsub from 'pubsub-js'
import axios from 'axios'

export default class index extends Component {
  search = async () => {
    // console.log(this.keywordNode.value)
    const {
      keywordNode: { value: keyword }
    } = this

    // 发生请求前通知App组件更新状态
    Pubsub.publish('search', { isFirst: false, isLoading: true })

    /**
     * 使用axios发送请求
    axios.get(`/api/search/users?q=${keyword}`).then(
      response => {
        console.log('成功', response.data)
        Pubsub.publish('search', { isLoading: false, users: response.data.items })
      },
      error => {
        console.error(error)
        Pubsub.publish('search', { isLoading: false, err: error.message })
      }
    )
    */

    // 使用fetch发送请求
    /* 未优化版本
    fetch(`/api/search/users?q=${keyword}`)
      .then(
        response => {
          console.log('联系服务器成功了', response)
          return response.json()
        },
        error => {
          console.log('联系服务器失败了', error)
          return new Promise(() => {})
        }
      )
      .then(
        response => {
          console.log('获取数据成功了', response)
        },
        error => {
          console.log('获取数据失败了', error)
        }
      )
      */

    /*
    fetch(`/api/search/users?q=${keyword}`)
      .then(response => {
        console.log('联系服务器成功了', response)
        return response.json()
      })
      .then(response => console.log('获取数据成功了', response))
      .catch(error => console.log('请求出错了', error))
      */

    try {
      const reponse = await fetch(`/api/search/users?q=${keyword}`)
      const data = await reponse.json()
      console.log(65, data)
      Pubsub.publish('search', { isLoading: false, users: data.items })
    } catch (error) {
      console.log('请求出错了', error)
      Pubsub.publish('search', { isLoading: false, err: error.message })
    }
  }

  render() {
    return (
      <div className="container">
        <section className="jumbotron">
          <h3 className="jumbotron-heading">Search Github Users</h3>
          <div className="row">
            <div className="col">
              <input
                className="form-control"
                ref={e => (this.keywordNode = e)}
                type="text"
                placeholder="enter the name you search"
              />
            </div>
            <div className="col">
              <button className="btn btn-primary" onClick={this.search}>
                Search
              </button>
            </div>
          </div>
        </section>
      </div>
    )
  }
}
